import tips from '../utils/tips.js'
import transformConfig from './config.js'

export default function http(url, config) {
    //重载
    if(typeof url === 'string') {
        config.url = url;
    } else if (typeof url === 'object') {
        config = url;
    }
    
    if(config.loading !== false) {
        tips.loading()
    }
    
    config = transformConfig(config);
    return request(config)
}

//发起请求
function request(config) {
    return new Promise((resolve, reject) => {
        wx.request({
            ...config,
            success(res) {
                tips.loaded();
                transformResponse(res, resolve, config)
            },
            fail() {
                tips.toast('请求失败！',3000)
                reject(config)
            },
            complete() {
                // tips.loaded()
            }
        })
    })
}

/**
 * 处理请求返回数据
 * @param {Object} response -请求返回数据
 * @param {function} resolve 
 */
function transformResponse(response, resolve, config) {
    if(response.statusCode == 200) {
        resolve(response.data)
    } else {
        errorStatusCode(response)
    }
}

function requestAgin(resolve, config) {
    request(config).then(data => {
        resolve(data)
    })
}

//处理错误状态码
function errorStatusCode (res) {
    let { statusCode, data} = res;
    
    if(statusCode) {
        switch (statusCode){
            case 404:
                tips.toast('404 Not Found！', 2500)
                break;
            case 408:
                tips.toast('请求超时!', 2500)
                break;
            case 500:
                tips.toast(`500 ${data && data.msg || 'Internal Server Error' }！`, 2500)
                break;
            case 502:
                tips.toast( `502 ${data && data.msg || 'Bad Gateway' } ！`, 2500)
                break;
            default:
                tips.toast(data && data.msg ? data.msg : `${statusCode} 服务器开小差！`, 2500)
                break;
        }
    } else {
        tips.toast(data && data.msg ? data.msg : '服务器开小差', 2500)
    }
}

//拓展请求
['get','post','put','patch','delete','head','options'].forEach(method => {
    http[method] = function(url, data, config = {}) {
        const options = {
            url,
            method: method,
            ...config
        }
        if(method == 'post' || method == 'put' || method == 'patch') {
            options.data = data;
        } else {
            options.params = data;
        }
        return http(options)
    }
})
